<template>
  <div class="login-container">
    <el-card class="login-card">
      <template #header>
        <div class="card-header">
          <h2>用户登录</h2>
        </div>
      </template>

      <el-form
        ref="loginFormRef"
        :model="loginForm"
        :rules="rules"
        label-width="0"
        class="login-form"
      >
        <el-form-item prop="username">
          <el-input
            v-model="loginForm.username"
            placeholder="用户名"
            :prefix-icon="User"
          />
        </el-form-item>

        <el-form-item prop="password">
          <el-input
            v-model="loginForm.password"
            type="password"
            placeholder="密码"
            :prefix-icon="Lock"
            show-password
          />
        </el-form-item>

        <div class="remember-forgot">
          <el-checkbox v-model="loginForm.remember">记住我</el-checkbox>
          <el-button link type="primary" @click="forgotPassword">忘记密码？</el-button>
        </div>

        <el-form-item>
          <el-button
            type="primary"
            class="login-button"
            :loading="loading"
            @click="handleLogin(loginFormRef)"
          >
            登录
          </el-button>
        </el-form-item>

        <div class="register-link">
          还没有账号？
          <router-link to="/register">立即注册</router-link>
        </div>
      </el-form>
    </el-card>
  </div>
</template>

<script>
import { login } from '@/api/user'
import { Lock, User } from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'
import { reactive, ref } from 'vue'
import { useRouter } from 'vue-router'
import { useStore } from 'vuex'

export default {
  name: 'LoginPage',
  setup() {
    const router = useRouter()
    const store = useStore()
    const loginFormRef = ref()
    const loading = ref(false)

    const loginForm = reactive({
      username: '',
      password: '',
      remember: false
    })

    const rules = {
      username: [
        { required: true, message: '请输入用户名', trigger: 'blur' },
        { min: 3, max: 20, message: '长度在 3 到 20 个字符', trigger: 'blur' }
      ],
      password: [
        { required: true, message: '请输入密码', trigger: 'blur' },
        { min: 6, max: 20, message: '长度在 6 到 20 个字符', trigger: 'blur' }
      ]
    }

    const handleLogin = async (formEl) => {
      if (!formEl) return
      await formEl.validate(async (valid) => {
        if (valid) {
          loading.value = true
          try {
            // 只发送 username 和 password 字段
            const { username, password } = loginForm
            const res = await login({ username, password })
            // 存储token和用户信息
            localStorage.setItem('token', res.token)
            store.commit('setUser', res)
            store.commit('setToken', res.token)
            
            ElMessage.success('登录成功')
            // 如果有重定向地址，则跳转到重定向地址
            const redirect = router.currentRoute.value.query.redirect
            router.push(redirect || '/')
          } catch (error) {
            // 错误消息已经在 request.js 中处理，这里不需要重复显示
            console.error('Login failed:', error)
          } finally {
            loading.value = false
          }
        }
      })
    }

    const forgotPassword = () => {
      ElMessage.info('请联系客服重置密码')
    }

    return {
      loginFormRef,
      loginForm,
      loading,
      rules,
      handleLogin,
      forgotPassword,
      User,
      Lock
    }
  }
}
</script>

<style lang="scss" scoped>
.login-container {
  min-height: 100vh;
  display: flex;
  align-items: center;
  justify-content: center;
  background-color: #f5f7fa;

  .login-card {
    width: 100%;
    max-width: 400px;
    margin: 20px;
    border-radius: 8px;
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);

    .card-header {
      text-align: center;
      
      h2 {
        margin: 0;
        font-size: 24px;
        color: #333;
      }
    }

    .login-form {
      padding: 20px 0;

      .remember-forgot {
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-bottom: 20px;
      }

      .login-button {
        width: 100%;
        padding: 12px 0;
      }

      .register-link {
        text-align: center;
        margin-top: 20px;
        color: #606266;

        a {
          color: #409EFF;
          text-decoration: none;

          &:hover {
            text-decoration: underline;
          }
        }
      }
    }
  }
}
</style> 